//
//  SleepActivityStatusViewModel.swift
//  DaRings
//
//  Created by 尹琼 on 2022/11/24.
//

import UIKit
import MYModule
import RxCocoa
import RxSwift

open class SleepActivityStatusViewModel: NSObject {
    
    
    /// collectionView 高度
    public let collectionViewHeight: CGFloat = 51.0
    
    public let UIRePlay = BehaviorRelay<SleepActivityStatusModel?>(value: nil)
    
    public init(providerRelay: BehaviorRelay<SleepProvider?>) {
        super.init()
        
        providerRelay.map {[weak self] in
            
            return self?.activityModel(of: $0?.curDayDetail)
            
        }.bind(to: UIRePlay).disposed(by: rx.disposeBag)
        
        
    }
    
    open func activityModel(of model: SleepModel?) ->SleepActivityStatusModel? {

        guard let sleepModel = model, let model = AmountActivityModel.day(date: sleepModel.date) else {
            return nil
        }
        
        let activitys = model.fullActicitys
 
        let UIModel = SleepActivityStatusModel()
        
        if let fallAsleepDate = sleepModel.fallAsleepDate,
           let wakeUpDate = sleepModel.awakeDate {
            
            UIModel.fallAsleep = fallAsleepDate.toString(.custom("MM/dd HH:mm"))
            UIModel.wakeUp = wakeUpDate.toString(.custom("MM/dd HH:mm"))
        }
        
        var subActivitys: [Int] = []
        var chartDatas: [SleepActivityStatusChartData] = []
        for activity in activitys {
            if subActivitys.count > 0 && subActivitys.count%5 == 0 {
                let chartData = SleepActivityStatusChartData(activitys: subActivitys)
                chartDatas.append(chartData)
                subActivitys.removeAll()
            }
            subActivitys.append(activity)
        }
        if !subActivitys.isEmpty {
            if subActivitys.count < 5 {
                // 补 0
                let addZero = (0 ..< (5 - subActivitys.count)).map { _ in 0 }
                subActivitys.append(contentsOf: addZero)
            }
            let chartData = SleepActivityStatusChartData(activitys: subActivitys)
            chartDatas.append(chartData)
        }
       
        UIModel.sleepingChartData = chartDatas
        
        return UIModel
    }

}

